package com.example.zookeeperlock.highlock;

import org.I0Itec.zkclient.ZkClient;

import java.util.List;

/**
 * @Author: zhangrongqing
 * @Date: 2020/9/1 11:11
 */
public abstract class AbstractLock {

    public final static String PATH = "/MYLOCK3";

    public static final String ADDRESS = "127.0.0.1:2181";

    public static final int SESSION_TIMEOUT = 1000;

    public final ZkClient zkClient = new ZkClient(ADDRESS, SESSION_TIMEOUT);

//    public final static ZkClient zkClient = MyZkClient.getInstance();


    public void getLock() {
        String threadName = Thread.currentThread().getName();
        if (tryLock()) {
            System.out.println(threadName + "获取锁");
        } else {
            System.out.println(threadName + "获取锁失败，等待锁");
            waitLock();
            getLock();
        }
    }

    public abstract Boolean tryLock();

    public abstract void waitLock();

    public abstract void releaseLock();

//    public Boolean tryLock(){
//        ZkClient client = MyZkClient.getInstance();
//        //判断根目录是否存在，不存在创建
//        boolean exists = client.exists(PATH);
//        if(!exists){
//            client.createPersistent(PATH);
//        }
//
//        return false;
//    }
}
